package data;

import java.util.HashMap;

import javax.media.opengl.GL;

import logic.TextureLoader;

import com.sun.opengl.util.texture.Texture;



public class Sprite implements Drawable {
	private Vector2 pos;
	protected Vector2 size;
	private Texture glTexture;
	private String filePath;
	private static int spriteNumber = 0;
	private int spriteID;
	private static HashMap<String,Texture> spriteTextures = new HashMap<String, Texture>();
	protected boolean isInit = false;
	public Sprite(Vector2 pos, Vector2 size, String filePath){
		this.pos = pos;
		this.size = size;
		this.spriteID = spriteNumber;
		this.filePath = filePath;
		Sprite.spriteNumber++;
	}
	@Override
	public boolean draw(GL gl) {
		this.glTexture.bind();
		gl.glPushMatrix();
		//System.out.println("scaleX: "+this.scale.x+"; scaleY: "+ this.scale.y);
		//gl.glScalef(0.5f, 0.5f, 1.0f);
		gl.glTranslatef(this.pos.x, this.pos.y, spriteID*0.00001f+0.00001f);
		gl.glScalef(size.x, size.y, 1.0f);
		gl.glColor3f(1.0f, 1.0f, 1.0f);
		gl.glBegin(GL.GL_QUADS);
			gl.glTexCoord2f(0.0f, 0.0f);
			gl.glVertex2f(-0.5f, -0.5f);
			gl.glTexCoord2f(1.0f, 0.0f);
			gl.glVertex2f(0.5f, -0.5f);
			gl.glTexCoord2f(1.0f, 1.0f);
			gl.glVertex2f(0.5f, 0.5f);
			gl.glTexCoord2f(0.0f, 1.0f);
			gl.glVertex2f(-0.5f, 0.5f);
		gl.glEnd();
		gl.glPopMatrix();
		return true;
	}
	/**
	 * returns the gl Texture of an image at the given location.
	 * if the path was loaded before, the image is not loaded again.
	 * @param textureFilePath
	 * @return texture
	 */
	private static Texture getTextureID(String textureFilePath){
		if(spriteTextures.containsKey(textureFilePath)){
			return spriteTextures.get(textureFilePath);
		}else{
			Texture texture = TextureLoader.load(textureFilePath);
			spriteTextures.put(textureFilePath, texture);
			return texture;
		}
	}
	/**
	 * loads a texture using.
	 * if the path was loaded before, the image is not loaded again.
	 * @param textureFilePath
	 */
	public static void loadTexture(String textureFilePath){
		getTextureID(textureFilePath);
	}
	/**
	 * sets the position of the Sprite (middle)
	 * @param x
	 * @param y
	 */
	public void setPosition(float x, float y){
		this.pos.set(x, y);
	}
	/**
	 * returns the position of the Sprite (middle)
	 * @return position
	 */
	public Vector2 getPosition(){
		return this.pos;
	}
	/**
	 * sets the image file an inits the sprite new
	 * @param filePath
	 */
	public void setImageFile(String filePath){
		this.filePath = filePath;
		init(null);
	}
	@Override
	public boolean init(GL gl) {
		this.glTexture = getTextureID(filePath);
		isInit = true;
		return true;
	}
}
